import gtk
import os
import xmmsclient.glib
import utils
from model import MlibModel
from constants import *
from xmmsclient import XMMS


class MLib(MlibModel):
    def __init__(self, xmms2):
        builder = gtk.Builder()
        builder.add_from_file("mlib.glade")
        builder.connect_signals(self)
        self.treeview = builder.get_object("detailedinfoview")
        self.selection = self.treeview.get_selection()
        self.selection.set_mode(gtk.SELECTION_MULTIPLE)
        self.xmms2 = xmms2
        MlibModel.__init__(self, self, builder)

    def add_to_playlist(self, *args):
        model, pathlist = self.selection.get_selected_rows()
        for path in pathlist:
            id = self.mlibfull[path][IDCOL]
            self.xmms2.playlist_add_id(id)

    def append_to_store(self, res):
        if res.iserror():
            print "get_info_from_id error"
            return
        info = res.value()
        utils.append_to_store(self.store, info)

    def get_info_from_id(self, res):
        if res.iserror():
            print "get_info_from_id error"
            return
        info = res.value()
        for id in info:
            self.xmms2.medialib_get_info(id, cb=self.append_to_store)

    def on_collview_row_activated(self, treeview, path, column):
        self.store.clear()
        model = treeview.get_model()
        parent = path[0]
        if parent == COLLVIEW_LIB:
            self.treeview.set_model(self.mlibfull)
        elif parent == COLLVIEW_PLAYLIST:
            playlist = model[path][COLLVIEW_COL_NAME]
            self.treeview.set_model(self.store)
            self.xmms2.playlist_list_entries(playlist,
                                             cb=self.get_info_from_id)
        else:
            print model[path]

    def quit(self, *args):
        gtk.main_quit()


xmms2 = XMMS("mlib")
try:
    xmms2.connect(os.getenv("XMMS_PATH"))
except Exception, e:
    print "[xmms2 client]: Could not connect to xmms2d"
    print e
    print "Aborting!"
    exit(1)
xmmsclient.glib.GLibConnector(xmms2)

MLib(xmms2)
gtk.main()
